package com.polaris.live.utils

import android.graphics.BitmapFactory
import java.io.FileInputStream

/**
 * WebpUtils
 *
 * @author Created by 半仙 on 2023/11/20/020 22:03
 */
object AnimatedUtils {

    fun isAnimatedImage(filePath: String): Boolean {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filePath, options)

        val mimeType = options.outMimeType ?: ""
        return mimeType == "image/gif" || mimeType == "image/webp"
    }

    fun isWebpAnimated(filePath: String): Boolean {
        val headerBytes = ByteArray(12)
        FileInputStream(filePath).use { inputStream ->
            if (inputStream.read(headerBytes, 0, 12) != 12) {
                // 读取文件头部分字节失败，不是有效的 WebP 文件
                return false
            }
        }

        // 检查文件头标识符
        val webpHeader = String(headerBytes, Charsets.US_ASCII)
        val webpIdentifier = byteArrayOf('W'.toByte(), 'E'.toByte(), 'B'.toByte(), 'P'.toByte())
        return webpHeader == "RIFF" && headerBytes.copyOfRange(8, 12).contentEquals(webpIdentifier)
    }
}